<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>eventBus</title>
  </head>
  <body>
    <div id="app">
      <new-todo></new-todo>
      <todo-list></todo-list>
    </div>
    <script src="../static/script/vue.js"></script>
    <script>
      let eventHub = new Vue({
        data() {
          return {
            todos: ['吃饭', '学习', '学习JavaScript', '学习css']
          }
        },
        created() {
          this.$on('add', this.addTodo)
          this.$on('delete', this.deleteTodo)
        },
        beforeDestroy() {
          this.$off('add', this.addTodo)
          this.$off('delete', this.deleteTodo)
        },
        methods: {
          addTodo(newTodo) {
            this.todos.push(newTodo)
          },
          deleteTodo(index) {
            this.todos.splice(index, 1)
          }
        }
      })

      let newTodo = {
        template: `<div>
            <input type="text" autofocus v-model="newtodo" @keyup.enter="add" />
            <button type="button" @click="add">add</button>
          </div>`,
          data() {
            return {
              newtodo: ''
            }
          },
          methods: {
            add() {
              eventHub.$emit('add', this.newtodo)
              this.newtodo = ''
            }
          }
      }

      let todoList = {
        template: `<ul>
            <li v-for="(item,index) in items">{{item}}
              <button type="button" @click="deleteItem(index)">X</button>
            </li>
          </ul>`,
        data() {
          return {
            items: eventHub.todos
          }
        },
        methods: {
          deleteItem(index) {
            eventHub.$emit('delete', index)
          }
        }
      }
      let app = new Vue({
        el: '#app',
        components: {
          newTodo,
          todoList,
        }
      })
    </script>
  </body>
</html>
